<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Logic;


use App\Common\HttpClient;
use App\Common\Logger;
use App\Common\Sql;
use App\Common\Tool;
use App\Exceptions\ApiException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class MiGuLogic extends Logic
{
    public static $gameID        = 111;
    public static $client_id     = '111';
    public static $client_secret = 'majiang';
    public static $grant_type    = 'client_credentials';
    public static $ticket_propid = 110000;
    public static $client_main   = 1;
    public static $client_sub    = 1;
    public static $version       = '1.0';
    public $user_id;

    public function getUserInfo()
    {
        $user_info = $this->get_migu_user_info($this->user_id);
        if (empty($user_info)) {
            throw new ApiException('MiguUserInfo can not be earn.', -500);
        }
        return $user_info;
    }


    //通过使用SDK提供的token 获取咪咕的唯一用户ID
    public function get_miguid_from_token($token)
    {
        $data               = array();
        $url                = env('MIGU_BASE_URL') . '/token';
        $data['timestamp']  = (string)$this->msectime();
        $data['gameId']     = (string)self::$gameID;
        $data['identityId'] = $token;
        $data['signature']  = $this->get_signature($data);
        $ret                = (new HttpClient())->MiGuPost($url, json_encode($data));
        if ($ret == false) {
            throw new ApiException('获取id失败');
        } else {
            $find = (array)json_decode($ret, true);
            if ($find['returnCode'] != '000000') {
                throw new ApiException($find['returnCode'] . ':' . $find['message'], -500);
            } else {
                return $this->user_id = $find['resultData']['userId'];
            }
        }
    }


    //获取服务器的token
//    public function get_access_token()
//    {
//        $key = 'migu_access_token';
//        $ret = Redis::get($key);
//        // 如果在redis里的access没有更新
//        if ($ret == false) {
//            $url                   = $this->base_url . '/oauth/token';
//            $data                  = array();
//            $data['client_id']     = $this->client_id;
//            $data['client_secret'] = $this->client_secret;
//            $data['grant_type']    = $this->grant_type;
//            $client                = new HttpClient();
//            $ret                   = $client->Post($url, $data);
//            dump($ret);
//            if ($ret == false) {
//                throw new ApiException('获取token失败',-6);
//            } else {
//                $find   = (array)json_decode($ret, true);
//                $token  = 'Bearer ' . (string)$find['access_token'];
//                $expire = (int)$find['expires_in'] - 5;
//                //还差5s时候就不往redis里更新缓存了
//                if ($expire > 0) {
//                    Redis::set($key,$token);
//                    Redis::expire($key,$expire);
//                }
//                return $token;
//            }
//        }
//        return (string)$ret;
//    }


    //已经注册的用户处理
    public function hasRegistered($row, $login_ip)
    {
        //该号已经注册过，直接登录
        if ($row[0]['status'] == 0) { //被禁号
            throw new ApiException('您的账号已经被管理员封禁，如有疑问请联系客服', 120);
        }
        $uid  = $row[0]['id'];
        $now  = time();
        $skey = md5($now);

//        $province   = "未知";
//        $city       = "未知";
//        $url_prefix = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=";
//        $url        = $url_prefix . $login_ip;
//        $client     = new HttpClient();
//        $ret        = $client->Get($url);
//        if ($ret == false) {
//        } else {
//            $find = (array)json_decode($ret, true);
//            if (!empty($find["ret"]) && $find['ret'] = 1) {
//                $province = $find["province"];
//                $city     = $find["city"];
//            }
//        }

        DB::beginTransaction();
        try {
            DB::table('t_player_info')->where('id', $uid)->update(['login_ip' => $login_ip, 'skey' => $skey]);
            DB::table('t_login_rec')->insert([
                'login_uid' => $uid,
                'login_type' => 2,
                'login_ip' => $login_ip,
//                'login_province' => $province,
//                'login_city' => $city
            ]);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new ApiException('咪咕登录失败', -6);
        }

        $migu_user_info                = $this->getUserInfo();

        $user_info                     = array();
        $user_info['uid']              = (int)$uid;
        $user_info['nick_name']        = $row[0]['nick_name'];
        $user_info['sex']              = (int)$row[0]['sex'];
        $user_info['avater_url']       = $row[0]['avater_url'];
        $user_info['room_ticket']      = (int)$migu_user_info['roomcard'];
        $user_info['gold']             = (int)$row[0]['gold'];
        $user_info['diamonds']         = (int)$migu_user_info['diamond'];
        $user_info['login_ip']         = $login_ip;
        $user_info['skey']             = $skey;
        $user_info['login_type']       = 3;
        $user_info['paiwei_score']     = (int)$row[0]['paiwei_score'];
        $ret_arr                       = $this->cal_paiwei_rank($user_info['paiwei_score']);
        $user_info['paiwei_rank']      = $ret_arr["paiwei_rank"];
        $user_info['paiwei_rank_name'] = $ret_arr["paiwei_rank_name"];
        $user_info['vip_id']           = $this->getVipId($migu_user_info);
        $user_info['vip_month_first']     = $this->checkFirstTime($migu_user_info);
        return $user_info;
    }


    //没有注册的用户处理
    public function noHasRegistered($ua, $migu_id, $login_ip)
    {
        //新账号，直接注册
        //创建用户
        $now                      = date('Y-m-d H:i:s', time());
        $new_user                 = array();
        $new_user["migu_id"]      = $migu_id;
        $new_user["nick_name"]    = $migu_id;
        $new_user["status"]       = 1;        // 0：为封号的, 1:表示账号可用
        $new_user["sex"]          = 0;
        $new_user["ua"]           = $ua;
        $new_user["gold"]         = 15000;
        $new_user["create_time"]  = $now;
        $new_user["update_time"]  = $now;
        $new_user["skey"]         = md5(time());
        $new_user["login_ip"]     = $login_ip;
        $new_user["paiwei_score"] = 0;

        try {
            $uid        = DB::table('t_player_info')->insertGetId($new_user);
//            $province   = "未知";
//            $city       = "未知";
//            $url_prefix = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=";
//            $url        = $url_prefix . $login_ip;
//            $client     = new HttpClient();
//            $ret        = $client->Get($url);
//            if ($ret == false) {
//            } else {
//                $find = (array)json_decode($ret, true);
//                if ($find["ret"] != 1) {
//                } else {
//                    $province = $find["province"];
//                    $city     = $find["city"];
//                }
//            }
            DB::table('t_login_rec')->insert([
                'login_uid' => $uid,
                'login_type' => $uid,
                'login_ip' => $uid,
//                'login_province' => $province,
//                'login_city' => $city,
            ]);
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new ApiException('注册用户失败', -6);
        }

        $migu_user_info                = $this->getUserInfo();

        $user_info                     = array();
        $user_info['uid']              = (int)$uid;
        $user_info['nick_name']        = $new_user["nick_name"];
        $user_info['sex']              = (int)$new_user['sex'];
        $user_info['avater_url']       = $migu_user_info['avatar'];
        $user_info['gold']             = (int)$new_user['gold'];
        $user_info['room_ticket']      = (int)$migu_user_info['roomcard'];
        $user_info['diamonds']         = (int)$migu_user_info['diamond'];
        $user_info['login_ip']         = $login_ip;
        $user_info['skey']             = $new_user['skey'];
        $user_info['login_type']       = 2;
        $user_info['paiwei_score']     = (int)$new_user['paiwei_score'];
        $ret_arr                       = $this->cal_paiwei_rank($user_info['paiwei_score']);
        $user_info['paiwei_rank']      = $ret_arr["paiwei_rank"];
        $user_info['paiwei_rank_name'] = $ret_arr["paiwei_rank_name"];
        $user_info['vip_id']           = $this->getVipId($migu_user_info);
        $user_info['vip_month_first']     = $this->checkFirstTime($migu_user_info);
        return $user_info;
    }

//    // 房卡消费
//    // 1:成功消费房卡 2.该用户房卡不足，可用钻石兑换 3.该用户钻石，房卡数量均不足
//    public function deduct_room_ticket($user_id, $num, $order_id)
//    {
//        $data                = array();
//        $url                 = $base_url . '/roomcard/deductRoomCards';
//        $data['timestamp']   = (string)$this->getMillisecond();
//        $data['userId']      = $user_id;
//        $data['quantity']    = $num;
//        $data['orderId']     = $order_id;
//        $data['gameId']      = $gameID;
//        $data['propId']      = $ticket_propid;
//        $data['clientId']    = $client_main;
//        $data['clientIdSub'] = $client_sub;
//        $data['version']     = $version;
//        $data['signature']   = get_signature($data);
//        //$header = array('Authorization'=>get_access_token());
//        $client   = new HttpClient();
//        $data_str = $this->m_json_encode($data);
//        $ret      = $client->PostRaw($url, $data_str, $header);
//        if ($ret == false) {
//            return false;
//        } else {
//            $find = (array)json_decode($ret, true);
//            if ($find['returnCode'] != '000000') {
//                throw new ApiException($find['returnCode'] . ':' . $find['message'], -500);
//            } else {
//                return $find['resultData']['result'];
//            }
//        }
//    }
//
//    //退还房卡
//    public function return_room_ticket($user_id, $num, $order_id)
//    {
//        $data                = array();
//        $url                 = $this->base_url . '/roomcard/returnRoomCards';
//        $data['timestamp']   = (string)$this->getMillisecond();
//        $data['userId']      = $user_id;
//        $data['quantity']    = $num;
//        $data['orderId']     = $order_id;
//        $data['gameId']      = $gameID;
//        $data['propId']      = $ticket_propid;
//        $data['clientId']    = $client_main;
//        $data['clientIdSub'] = $client_sub;
//        $data['version']     = $version;
//        $data['signature']   = get_signature($data);
//        //$header = array('Authorization'=>get_access_token());
//        $client   = new HttpClient();
//        $data_str = $this->m_json_encode($data);
//        $ret      = $client->PostRaw($url, $data_str, $header);
//        if ($ret == false) {
//            return false;
//        } else {
//            $find = (array)json_decode($ret, true);
//            if ($find['returnCode'] != '000000') {
//                $this->returnError(-500, $find['returnCode'] . ':' . $find['message']);
//            } else {
//                return $find['resultData']['result'];
//            }
//        }
//    }


    //根据userid获取用户信息
    public function get_migu_user_info($user_id)
    {
        $data              = array();
        $url               = env('MIGU_BASE_URL') . '/userInfo';
        $data['timestamp'] = (string)$this->msectime();
        $data['gameId']    = (string)self::$gameID;
        $data['userId']    = $user_id;
        $data['signature'] = $this->get_signature($data);
        //$header = array('Authorization'=>get_access_token());
        $client = new HttpClient();
        $ret    = $client->MiGuPost($url, json_encode($data));
        if ($ret == false) {
            return false;
        } else {
            $find = (array)json_decode($ret, true);
            if ($find['returnCode'] != '000000') {
                throw new ApiException($find['returnCode'] . ':' . $find['message'], -500);
            } else {
                return $find['resultData'];
            }
        }
    }


    //生成签名
    private function get_signature($body)
    {
        $str = "timestamp=" . (string)$body['timestamp'];
        foreach ($body as $key => $value) {
            if ($key != 'timestamp') {
                $str = $str . "&" . $key . "=" . $value;
            }
        }
        return strtoupper(md5($str));
    }

    private function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    }


    private function cal_paiwei_rank($paiwei_score)
    {
        $object = DB::table('t_rank_conf')->where('min_score', '<=', $paiwei_score)->where('max_score', '>', $paiwei_score)->first();
//        $row = $this->mysql->find("SELECT * from rank_config where $paiwei_score >= min_score AND $paiwei_score < max_score;");
        if (empty($object)) {
            Logger::instance()->error(Tool::getUri(), "get paiwei error.\n");;
            $rank                     = array();
            $rank['paiwei_rank']      = 0;
            $rank['paiwei_rank_name'] = "无";
            return $rank;
        }
        $rank                     = array();
        $rank['paiwei_rank']      = (int)$object->id;
        $rank['paiwei_rank_name'] = $object->name;
        return $rank;
    }


    private function getVipId($vipList)
    {
        if (empty($vipList['vipList'])) {
            return [];
        }
        return array_column($vipList['vipList'], 'vipId');
    }


    private function checkFirstTime($migu_info)
    {
        if (empty($migu_info['vipList'])) {
            return 0;
        }
        $key = 'Miguvip'.date('Ym');
        if (!empty(Redis::hGet($key,$this->user_id))) {
            return 0;
        } else {
            Redis::hSet($key,$this->user_id,1);
            Redis::expire($key,strtotime(date('Y-m',strtotime('+ 1 month'))) - time());
            return 1;
        }
    }



}